package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApLikesBehaviorService;
import com.heima.common.exception.CustException;
import com.heima.model.behavior.dtos.LikesBehaviorDTO;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApLikesBehavior;
import com.heima.model.common.constants.article.HotArticleConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.app.UpdateArticleMess;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@Slf4j
public class ApLikesBehaviorServiceImpl implements ApLikesBehaviorService {
    @Autowired
    MongoTemplate mongoTemplate;
    @Autowired
    ApBehaviorEntryService apBehaviorEntryService;
    @Autowired
    RabbitTemplate rabbitTemplate;

    /**
     * 点赞或取消点赞
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult like(LikesBehaviorDTO dto) {
        // 1.校验参数
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "点赞需要登录");
        }
        // 1.2 文章id 不能为空
        if (dto.getArticleId() == null) {
            CustException.cust(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST, "文章不能为空");
        }
        // 1.3 点赞方式只能是0或1

        // 2.根据当前登录用户id查询行为实体对象
//        Query query = Query.query(Criteria.where("refId").is(user.getId()));
//        ApBehaviorEntry behaviorEntry = mongoTemplate.findOne(query, ApBehaviorEntry.class);
        ApBehaviorEntry entry = apBehaviorEntryService.findByUserIdOrEquipmentId(user.getId(), dto.getEquipmentId());
        if (entry == null) {

            CustException.cust(AppHttpCodeEnum.SERVER_ERROR);
        }
        return getResponseResult(dto, entry);

    }

    private ResponseResult getResponseResult(LikesBehaviorDTO dto, ApBehaviorEntry behaviorEntry) {
        String entryId = behaviorEntry.getId();
// 3. 如果是点赞操作  判断是否已经点过赞
        Short operation = dto.getOperation();
        if (operation == null || (operation != 0 && operation != 1)) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "operation必须为0或1");
        }

        if (operation == 0) {
            if (entryId != null) {
                Query query1 = Query.query(Criteria.where("entryId").is(entryId).and("articleId").is(dto.getArticleId()));
                ApLikesBehavior likesBehavior = mongoTemplate.findOne(query1, ApLikesBehavior.class);
                // 4. 没有点过赞则 像mongo点赞集合中 添加点赞数据
                if (likesBehavior == null) {
                    ApLikesBehavior apLikesBehavior = new ApLikesBehavior();
                    apLikesBehavior.setCreatedTime(new Date());
                    apLikesBehavior.setEntryId(entryId);
                    apLikesBehavior.setOperation((short) 0);
                    apLikesBehavior.setArticleId(dto.getArticleId());
                    apLikesBehavior.setType(dto.getType());
                    mongoTemplate.save(apLikesBehavior);

                    //添加文章点赞发送消息
                    UpdateArticleMess mess = new UpdateArticleMess();
                    mess.setArticleId(dto.getArticleId());
                    mess.setAdd(dto.getOperation() == 0 ? 1 : -1);
                    mess.setType(UpdateArticleMess.UpdateArticleType.LIKES);
                    rabbitTemplate.convertAndSend(HotArticleConstants.HOT_ARTICLE_SCORE_BEHAVIOR_QUEUE, JSON.toJSONString(mess));
                    log.info("点赞行为 发送消息 ==>{}",JSON.toJSONString(mess));
                    return ResponseResult.okResult(apLikesBehavior);
                }
                CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "请不要重复点赞");
            }
        }
// 5. 如果是取消点赞操作  在mongo点赞集合中 删除对应点赞数据
        Query query1 = Query.query(Criteria.where("entryId").is(entryId).and("articleId").is(dto.getArticleId()));
        mongoTemplate.remove(query1, ApLikesBehavior.class);
        return ResponseResult.okResult();
    }
}
